import React, { useEffect, useRef, useState } from 'react';
import { useLocation,useNavigate } from 'react-router-dom';
import { CloseOutline,SoundOutline,SoundMuteOutline,VideoOutline } from 'antd-mobile-icons'

const VideoChat = () => {
  const localVideoRef = useRef();
  const navigate = useNavigate();
  const remoteVideoRef = useRef();
  const location = useLocation();
  const [status, setStatus] = useState('disconnected');
  const pc = useRef();
  const ws = useRef();
  const roomId = location.search.split('=')[1];
  const name = decodeURIComponent(location.search.split('&')[1].split('=')[1]);
  const [isCameraOn, setIsCameraOn] = useState(true);
  const [isMicrophoneOn, setIsMicrophoneOn] = useState(true);
  const [elapsedTime, setElapsedTime] = useState(0);
  const intervalRef = useRef(null);

  // 初始化媒体和WebSocket
  useEffect(() => {
    
    navigator.mediaDevices.getUserMedia({ video: true, audio: true })
     .then(stream => {
        localVideoRef.current.srcObject = stream;
        if (pc.current) pc.current.addTrack(stream.getTracks()[0], stream);
      })
     .catch(console.error);

    return () => {
      if (pc.current) pc.current.close();
      if (ws.current) ws.current.close();
    };
  }, []);

  // 初始化PeerConnection
  const createPeerConnection = () => {
    const config = {
      iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
    };
    pc.current = new RTCPeerConnection(config);

    pc.current.onicecandidate = ({ candidate }) => {
      if (candidate) {
        ws.current.send(JSON.stringify({ type: 'candidate', candidate }));
      }
    };

    pc.current.ontrack = (e) => {
      remoteVideoRef.current.srcObject = e.streams[0];
    };

    // 添加本地音视频轨道
    const localStream = localVideoRef.current.srcObject;
    if (localStream) {
      localStream.getTracks().forEach(track => {
        pc.current.addTrack(track, localStream);
      });
    }
  };

  // 加入房间
  const joinRoom = () => {
    ws.current = new WebSocket('ws://172.20.10.2:8010');
    ws.current.onmessage = async (message) => {
      const data = JSON.parse(message.data);
      switch (data.type) {
        case 'offer':
          if (pc.current) {
            await pc.current.setRemoteDescription(data.offer);
            const answer = await pc.current.createAnswer();
            await pc.current.setLocalDescription(answer);
            ws.current.send(JSON.stringify({ type: 'answer', answer }));
          }
          break;
        case 'answer':
          if (pc.current) {
            await pc.current.setRemoteDescription(data.answer);
          }
          break;
        case 'candidate':
          if (pc.current) {
            pc.current.addIceCandidate(new RTCIceCandidate(data.candidate));
          }
          break;
      }
    };

    ws.current.onopen = () => {
      ws.current.send(JSON.stringify({ type: 'join', roomId }));
      // 确保在getUserMedia完成后再创建PeerConnection
      const checkStream = () => {
        if (localVideoRef.current.srcObject) {
          createPeerConnection();
          setStatus('connected');
          createOffer();
        } else {
          setTimeout(checkStream, 100);
        }
      };
      checkStream();
    };
  };

  // 创建Offer
  const createOffer = async () => {
    if (pc.current) {
      const offer = await pc.current.createOffer();
      await pc.current.setLocalDescription(offer);
      ws.current.send(JSON.stringify({ type: 'offer', offer }));
    }
  };

  // 开关摄像头
  const toggleCamera = () => {
    const stream = localVideoRef.current.srcObject;
    if (stream) {
      stream.getVideoTracks().forEach(track => {
        track.enabled = !isCameraOn;
      });
      setIsCameraOn(!isCameraOn);
    }
  };

  // 开关麦克风
  const toggleMicrophone = () => {
    const stream = localVideoRef.current.srcObject;
    if (stream) {
      stream.getAudioTracks().forEach(track => {
        track.enabled = !isMicrophoneOn;
      });
      setIsMicrophoneOn(!isMicrophoneOn);
    }
  };

  // 自动化加入房间
  useEffect(() => {
    if (status === 'disconnected') {
      joinRoom();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useEffect(() => {
    if (status === 'connected') {
      intervalRef.current = setInterval(() => {
        setElapsedTime(prevTime => prevTime + 1);
      }, 1000);
    } else {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    }
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [status]);

  // 格式化时间
  const formatTime = (time) => {
    const minutes = Math.floor(time / 60);
    const seconds = time % 60;
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  };
  return (
    <div style={{height:'100%'}}>
      <div style={{ position: 'relative', width: '100%' ,margin: '10px' }}>
        <video ref={remoteVideoRef} autoPlay style={{ width: '100%' }} />
        <video
          ref={localVideoRef}
          autoPlay
          muted
          style={{
            position: 'absolute',
            top: '10px',
            right: '10px',
            width: '100px',
            zIndex: 1
          }}
        />
      </div>
      <div style={{width:'100%',textAlign:'center',height:'200px'}}>
        <p>{name}</p>
        <p>{formatTime(elapsedTime)}</p>
      </div>
      <div style={{width:'100%',display:'flex',justifyContent:'space-around',alignItems:'center',marginTop:'200px'}}>
      <button onClick={()=>{navigate('/tar/xiaoxi/dian')}} style={{width:'80px',height:'80px',background:'#fff',border:'none',backgroundColor:'#E91E63',color:'#fff',borderRadius:'50%'}}>
      <CloseOutline />
      </button>
      <button onClick={toggleCamera} style={{width:'80px',height:'80px',background:'#fff',border:'none',backgroundColor:'#9C27B0',color:'#fff',borderRadius:'50%'}}>
        {isCameraOn ? <VideoOutline /> : <VideoOutline />}
      </button>
      <button onClick={toggleMicrophone} style={{width:'80px',height:'80px',background:'#fff',border:'none',backgroundColor:'#FF9800',color:'#fff',borderRadius:'50%'}}>
        {isMicrophoneOn ? <SoundOutline /> : <SoundMuteOutline />}
      </button>
      </div>
      
    </div>
  );
};

export default VideoChat;